package com.hinner.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.hinner.entity.User;
import com.hinner.exception.CustomException;
import com.hinner.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt拦截器，每次访问url时，会先进入控制器，在进入控制器之前先进入拦截器
 * 这个jwt拦截器是专门来验证token的
 * 也就是说，每次前端访问后端端口时，必须携带正确的token参数，后端拦截器成功监测到才可以放行。
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 解决：前端成功携带token，后端拿不到token，产生跨域的问题
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())){
            log.info("这是OPTIONS的请求方法，直接放行");
            return true;
        }


        //1.获取token
        String token;
        token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }

        //2.验证token
        if (StrUtil.isBlank(token)) {
            log.info("jwt验证token:{}",token);
            throw new CustomException("无token,请检查");
        }
        String userId;
        User user;
        try {
            userId = JWT.decode(token).getAudience().get(0);
            user = userService.getById(Integer.parseInt(userId));
        } catch (Exception e) {
            String errMsg = "token验证失败，请重新登录";
            log.error(errMsg + " ,token=" + token, e);
            throw new CustomException(errMsg);
        }
        if (user == null) {
            throw new CustomException("用户不存在");
        }
        // 密码也加token了，也要验证下: 把数据库密码拿出来token加密下，然后和传入的token做匹配
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new CustomException("token验证失败，请重新登录");
        }
        log.info("token验证成功，后台放行了~~~~~");
        return true;
    }

}
